package com.lagou.demo.service.impl;

import com.lagou.demo.dao.TokenDao;
import com.lagou.demo.pojo.User;
import com.lagou.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @Classname IUserService
 * @Description TODO
 * @Date 2020/12/14 19:50
 * @Created by yang
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public boolean checkToken(String token) {
        User token1 = new User();
        token1.setToken(token);
        try {
            token1 = findOne(token1);
            if (token1 != null) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Transactional
    @Override
    public void insertUser(String email, String passwd) {
        User entity = new User();
        entity.setVersion(1);
        entity.setEmail(email);
        entity.setPasswd(passwd);
        entity.setToken(UUID.randomUUID().toString().replaceAll("-", ""));
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        tokenDao.save(entity);
    }

    @Transactional
    @Override
    public void save(User user) {
        if (user != null) {
            tokenDao.save(user);
        }
    }

    @Override
    public User findById(Long id) {
        Optional<User> byId = tokenDao.findById(id);
        User token = byId.get();
        return token;
    }

    @Override
    public User findOne(User token) {
        Example<User> example = Example.of(token);
        Optional<User> one = tokenDao.findOne(example);
        User o = one.get();
        return o;
    }

    @Transactional
    @Override
    public void deleteById(Long id) {
        tokenDao.deleteById(id);
    }

    @Override
    public List<User> findAll() {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<User> all = tokenDao.findAll(sort);
        return all;
    }

}
